package com.aaron.crowd.mvc.interceptor;

import com.aaron.crowd.constant.CrowdConstant;
import com.aaron.crowd.entity.Admin;
import com.aaron.crowd.exception.AccessForbiddenException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @BelongsProject: atcrowdfuncding
 * @BelongsPackage: com.aaron.crowd.mvc.interceptor
 * @author: Andy
 * @date: 2021.3.30 08:45
 * @Description: 登录拦截器
 * @since JDK 1.8
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1、通过request对象获得Session对象
        HttpSession session = request.getSession();

        // 2、尝试从Session域中获取Admin对象
        Admin admin = (Admin) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN);

        // 3、前端 admin 对象是否为空
        if (admin == null){
            System.err.println("======登录失败======");
            //  4、抛出异常
            throw new AccessForbiddenException(CrowdConstant.MESSAGE_ACCESS_FORBIDDEN);
        }
        // 5、如果 Admin 对象不为空，则返回 true 放行
        System.err.println("======登录成功======");
        return true;
    }

}
